package com.tan00xu.handler;

import com.alibaba.fastjson.JSON;
import com.tan00xu.pojo.User;
import com.tan00xu.service.TokenService;
import com.tan00xu.service.impl.TokenServiceImpl;
import com.tan00xu.utils.CmdOutputInformationUtils;
import com.tan00xu.utils.UserThreadLocal;
import com.tan00xu.vo.ErrorCode;
import com.tan00xu.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j//添加日志
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
            在执行controller方法（Handler）之前执行
            1. 需要判断请求的接口路径，是否为HandlerMethod(Controller方法)
            2. 判断token是否为空，如果为空，未登录，则拦截
            3. 如果token不为空，进行登录验证
            4. 认证通过，放行
         */
        if (!(handler instanceof HandlerMethod)) {
            // 不是HandlerMethod，不需要进行拦截
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("请求地址request uri:{}",requestURI);
        log.info("请求方式request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if(StringUtils.isBlank(token)){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            // 返回json数据
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        // 判断token是否解析成功
        User user = tokenService.checkToken(token);
        if (user == null) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            // 返回json数据
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        //登录验证通过，放行
        UserThreadLocal.set(user);
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除线程变量中的用户信息，避免内存泄漏
        UserThreadLocal.remove();
    }
}
